package com.competition.commgr.controller;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.competition.commgr.domain.vo.CompetitionItemVo;
import com.competition.common.config.RuoYiConfig;
import com.competition.framework.config.ServerConfig;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.competition.common.annotation.Log;
import com.competition.common.core.controller.BaseController;
import com.competition.common.core.domain.AjaxResult;
import com.competition.common.enums.BusinessType;
import com.competition.commgr.domain.Competitionsessions;
import com.competition.commgr.service.ICompetitionsessionsService;
import com.competition.common.utils.poi.ExcelUtil;
import com.competition.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 赛项届次Controller
 * 
 * @author ruoyi
 * @date 2025-01-29
 */
@RestController
@RequestMapping("/commgr/competitionsessions")
public class CompetitionsessionsController extends BaseController
{
    @Autowired
    private ICompetitionsessionsService competitionsessionsService;

    @Autowired
    private RuoYiConfig ruoyiConfig;

    @GetMapping("/suggestions")
    public AjaxResult getSuggestions(@RequestParam String keyword) {
        List<Competitionsessions> suggestions = competitionsessionsService.getSessionSuggestions(keyword);
        return AjaxResult.success(suggestions);
    }

    /**
     * 查询赛项届次列表
     */
    @PreAuthorize("@ss.hasPermi('commgr:competitionsessions:list')")
    @GetMapping("/list")
    public TableDataInfo list(Competitionsessions competitionsessions)
    {
        startPage();
        List<Competitionsessions> list = competitionsessionsService.selectCompetitionsessionsList(competitionsessions);
        return getDataTable(list);
    }

    /**
     * 导出赛项届次列表
     */
    @PreAuthorize("@ss.hasPermi('commgr:competitionsessions:export')")
    @Log(title = "赛项届次", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Competitionsessions competitionsessions)
    {
        List<Competitionsessions> list = competitionsessionsService.selectCompetitionsessionsList(competitionsessions);
        ExcelUtil<Competitionsessions> util = new ExcelUtil<Competitionsessions>(Competitionsessions.class);
        util.exportExcel(response, list, "赛项届次数据");
    }

    /**
     * 获取赛项届次详细信息
     */
    @PreAuthorize("@ss.hasPermi('commgr:competitionsessions:query')")
    @GetMapping(value = "/{sessionId}")
    public AjaxResult getInfo(@PathVariable("sessionId") Long sessionId)
    {
        return success(competitionsessionsService.selectCompetitionsessionsBySessionId(sessionId));
    }

    /**
     * 新增赛项届次
     */
    @PreAuthorize("@ss.hasPermi('commgr:competitionsessions:add')")
    @Log(title = "赛项届次", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Competitionsessions competitionsessions)
    {
        return toAjax(competitionsessionsService.insertCompetitionsessions(competitionsessions));
    }

    /**
     * 修改赛项届次
     */
    @PreAuthorize("@ss.hasPermi('commgr:competitionsessions:edit')")
    @Log(title = "赛项届次", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Competitionsessions competitionsessions)
    {
        return toAjax(competitionsessionsService.updateCompetitionsessions(competitionsessions));
    }

    /**
     * 删除赛项届次
     */
    @PreAuthorize("@ss.hasPermi('commgr:competitionsessions:remove')")
    @Log(title = "赛项届次", businessType = BusinessType.DELETE)
	@DeleteMapping("/{sessionIds}")
    public AjaxResult remove(@PathVariable Long[] sessionIds)
    {
        return toAjax(competitionsessionsService.deleteCompetitionsessionsBySessionIds(sessionIds));
    }

    /**
     * 实现文件下载功能
     */
    @PostMapping("/download")
    public void download(Competitionsessions competitionsessions, HttpServletResponse response)
    {
        String fileName = competitionsessions.getSessionFile();
        String filePath = Paths.get(ruoyiConfig.getFilePath(), fileName).toString();

        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");

        try {
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()).replace("+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");

            Path file = Paths.get(filePath);
            if (Files.exists(file)) {
                Files.copy(file, response.getOutputStream());
                response.getOutputStream().flush();
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @PreAuthorize("@ss.hasPermi('commgr:competitionsessions:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<Competitionsessions> util = new ExcelUtil<Competitionsessions>(Competitionsessions.class);
        List<Competitionsessions> list = util.importExcel(file.getInputStream());
        System.out.println(list);
        String operName = getUsername();
        String message = competitionsessionsService.importCompetitionitem(list, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<Competitionsessions> util = new ExcelUtil<Competitionsessions>(Competitionsessions.class);
        util.importTemplateExcel(response, "比赛届次数据");
    }
}
